//
//  MTCAlreadyAddConcreteViewController.m
//  ERP
//
//  Created by goldeney on 15/4/21.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MTCAlreadyAddConcreteViewController.h"

#import "MJRefresh.h"
#import "MTCAlreadyAddConcreteViewCell.h"
#import "UITableView+Custom.h"
#import "RKTabView.h"
#import "GEInputTableViewCell.h"

#import "JGActionSheet.h"
#import "GEUIAlertView.h"

#import "NSDictionary+DataFormat.h"
#import "NSKeyedArchiverUserLogin.h"

@interface MTCAlreadyAddConcreteViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (nonatomic,strong) NSString *concreteID;

@property (nonatomic,assign) BOOL isShowOperationButton;

@end

@implementation MTCAlreadyAddConcreteViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"方量追加"];
        
        NSArray *mainMenuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_HTGL_FLZJ_CZ"];
        if (mainMenuArray.count>0) {
            self.isShowOperationButton = YES;
            UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStyleDone target:self
                                                                          action:@selector(addConcreteSelector:)];
            self.navigationItem.rightBarButtonItem = leftButton;
        }
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getPassingParameter:(id)object
{
    if ([object isKindOfClass:[NSString class]])
        self.concreteID = object;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    [self setupRefresh];
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
}


#pragma mark 方量操作

//新增方量
- (void)addConcreteSelector:(id)sender
{
    GEUIAlertView *dialog = [[GEUIAlertView alloc] initWithTitle:@"方量新增" message:@"请输入追加方量（单位:立方）" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"添加",nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    dialog.delegate = self;
    dialog.tag = 1;
    
    UITextField *textField = [dialog textFieldAtIndex:0];
    textField.delegate = self;
    textField.placeholder = @"方量";
    [dialog show];
    
}

//修改方量
- (void)modifConcreteSelector:(id)sender
{
    GEUIAlertView *dialog = [[GEUIAlertView alloc] initWithTitle:@"方量修改" message:@"请输入修改方量（单位:立方）" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"修改",nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    dialog.delegate = self;
    dialog.tag = 2;
    dialog.object = sender;
    
    UITextField *textField = [dialog textFieldAtIndex:0];
    textField.delegate = self;
    textField.placeholder = @"方量";
    [dialog show];
}

//删除方量
//- (void)deleteConcreteSelector:(id)sender
//{
//    UIButton *itemButton = sender;
//    NSDictionary *mDictionary = [self.resultData objectAtIndex:itemButton.tag];
//    
//    JGActionSheet *simple = [JGActionSheet actionSheetWithSections:@[[JGActionSheetSection sectionWithTitle:@"方量删除" message:@"方量删除后将无法恢复，确认删除该方量吗？" buttonTitles:@[@"删除"] buttonStyle:JGActionSheetButtonStyleRed], [JGActionSheetSection sectionWithTitle:nil message:nil buttonTitles:@[@"取消"] buttonStyle:JGActionSheetButtonStyleCancel]]];
//    [simple setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
//        NSLog(@"%ld===%ld",indexPath.section ,indexPath.row);
//        [sheet dismissAnimated:YES];
//        //删除方量
//        if (indexPath.section == 0 && indexPath.row == 0) {
//            [self deleteNetWorkContractNumberData:mDictionary];
//        }
//    }];
//    [simple showInView:self.navigationController.view animated:YES];
//
//}

#pragma UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // return NO to not change text
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if(!basicTest) return NO;
    
    if(range.location == 0) if ([string isEqualToString:@"0"]) return NO;
    
    return YES;
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    UITextField *textField = [alertView textFieldAtIndex:0];
    
    if (alertView.tag == 1 && buttonIndex == 1) {//新增方量
        if([textField.text integerValue] <= 0) [self addConcreteSelector:nil];
        else [self addNetWorkContractNumberData:textField.text];
            
    } else if (alertView.tag == 2 && buttonIndex == 1){ //修改方量
        GEUIAlertView *geAlertView = (GEUIAlertView*)alertView;
        UIButton *itemButton = geAlertView.object;
        NSDictionary *mDictionary = [self.resultData objectAtIndex:itemButton.tag];
        
        if([textField.text integerValue] <= 0) [self modifConcreteSelector:itemButton];
        else [self modifNetWorkContractNumberData:mDictionary number:textField.text];
    }
}

#pragma mark 网络获取数据

- (void)getNetWorkData
{
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_FLZJ_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"合同ID" value:self.concreteID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView headerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            [self.resultData removeAllObjects];
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无追加方量" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self getNetWorkData];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.resultData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *model = [self.resultData objectAtIndex:section];
    NSInteger review = [model objectFormatIntegerForKey:@"Review"];
    if (review == 0 && self.isShowOperationButton) return 1;
    else return 1;//已审核状态，不可修改和删除
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        static NSString *CellIdentifierOne = @"MTCAlreadyAddConcreteViewCell";
        MTCAlreadyAddConcreteViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
        if (!cell){
            cell = [[MTCAlreadyAddConcreteViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSDictionary *model = [self.resultData objectAtIndex:indexPath.section];
        NSString *CZRY = [model objectFormatStringForKey:@"操作人" defaults:@"无操作人"];
        cell.CZRYLabel.text = CZRY;
        cell.CZRQLabel.text = [model objectFormatStringForKey:@"操作时间" defaults:@"未知"];
        cell.FLLabel.text = [model objectFormatStringForKey:@"追加方量" format:@"%@方" defaults:@"未知"];
        cell.ZTLabel.text = [model objectFormatStringForKey:@"审核状态" defaults:@"未知"];
        
//        NSString *SHRY = [model objectFormatStringForKey:@"审核人员" defaults:@"未知"];
//        
//        NSString *SHSJ = [model objectFormatStringForKey:@"审核时间" defaults:@"未知"];
//        
//        NSInteger Review = [model objectFormatIntegerForKey:@"Review"];
//        NSString *string = nil;
//        if (Review == 1) { //已审核
////            string = [NSString stringWithFormat:@"<font size=\"4px\"><font color=\"red\">%@</font>已在%@审核通过了%@发起的%@方砼的申请,该方量目前不可修改或删除。</font>",SHRY,SHSJ,CZRY,ZJFL];
//            string = [NSString stringWithFormat:@"%@已在%@审核通过了%@发起的%@方砼的申请，该方量目前不可修改或删除。",SHRY,SHSJ,CZRY,ZJFL];
//        } else { //未审核
//            string = [NSString stringWithFormat:@"%@发起的%@方砼的申请正在等待审核，当前可以修改或删除追加的方量。",CZRY,ZJFL];
//        }
        
//        NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
//        cell.TSWZLabel.attributedText = attrStr;
//        cell.TSWZLabel.text = string;
        return cell;
        
    } else {
        static NSString *TableSampleIdentifier = @"MTCAlreadyAddConcreteViewCellButton";
        GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableSampleIdentifier];
        if (!cell){
            cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        RKTabItem *tabItem1 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"toolbar_favorite_highlighted"]];
        tabItem1.titleString = @"修改";
        tabItem1.titleFont = [UIFont systemFontOfSize:12];
        tabItem1.tag = indexPath.section;
        [tabItem1 addTarget:self selector:@selector(modifConcreteSelector:)];
        
        RKTabItem *tabItem2 = [RKTabItem createUsualItemWithImageEnabled:nil imageDisabled:[UIImage imageNamed:@"message_add_background_highlighted"]];
        tabItem2.titleString = @"删除";
        tabItem2.titleFont = [UIFont systemFontOfSize:12];
        tabItem2.tag = indexPath.section;
//        [tabItem2 addTarget:self selector:@selector(deleteConcreteSelector:)];
        
        RKTabView *titledTabsView = [[RKTabView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth - 20, 48)];
        titledTabsView.titlesFontColor = [UIColor grayColor];
        titledTabsView.tabItems = @[tabItem1, tabItem2];
        titledTabsView.drawSplitLine = YES;
        titledTabsView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:titledTabsView];
        
        //添加分割线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth - 20, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
        [cell.contentView addSubview:lineView];
        
        return cell;
    }
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//   if (indexPath.row == 0) return 52;
//   else return 48;
    return 52;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 10;
    else return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == [self numberOfSectionsInTableView:tableView] - 1) return 10;
    else return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


#pragma mark
#pragma mark - 网络提交数据

//网络方量新增
- (void)addNetWorkContractNumberData:(NSString*)number
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在添加"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_FLZJ_AU"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"合同ID" value:self.concreteID];
    [content addParameterKey:@"ID" value:@"0"];
    [content addParameterKey:@"追加方量" value:number];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"添加成功"];
            NSDictionary *mDictionary = [firstArray firstObject];
            [self.resultData insertObject:mDictionary atIndex:0];
            [self.tableView reloadData];
            if (self.resultData.count > 0)
                [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            
        } else {
            [self showErrorHUDText:@"添加失败"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"添加失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
    
}


//网络方量删除
//- (void)deleteNetWorkContractNumberData:(NSDictionary*)numberDic
//{
//    //获取用户登录信息
//    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
//    NSString *numberID = [numberDic objectFormatStringForKey:@"ID"];
//    
//    NSString *where = [NSString stringWithFormat:@"@Type=''D'', @合同ID=%@, @追加方量表ID=%@, @操作人=''%@''",
//                       self.concreteID,numberID,userInfo.username];
//    
//    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在删除"];
//    ServiceConnect *content = [[ServiceConnect alloc] initWithERPWhereOrg:0 type:59 where:where];
//    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
//        [HUD dismissAnimated:YES];//关闭进度框
//        
//        //添加数据，刷新页面
//        NSArray *firstArray = nil;
//        if(result.resultArray && result.resultArray.count>0)
//            firstArray = [result.resultArray firstObject];
//        
//        //数据处理
//        if(firstArray && firstArray.count>0){
//            [self showSuccessHUDText:@"删除成功"];
//            [self.resultData removeObject:numberDic];
//            [self.tableView reloadData];
//            if (self.resultData.count <= 0)
//                [self.tableView setTableViewNotDataDrawText:@"暂无追加方量" isShow:YES];
//            
//        } else {
//            [self showErrorHUDText:@"删除失败"];
//        }
//        
//    } failed:^(NSError *error, NSDictionary *userInfo) {
//        NSLog(@"=====%@",error);
//        [HUD dismissAnimated:YES];//关闭进度框
//        [self showErrorHUDText:@"删除失败"];
//        
//    } abnormal:^(NSError *error, NSDictionary *userInfo) {
//        NSLog(@"=====%@",error);
//        [HUD dismissAnimated:YES];//关闭进度框
//        [self showErrorHUDText:@"网络异常"];
//        
//    }];
//    
//}

//网络方量修改
- (void)modifNetWorkContractNumberData:(NSDictionary*)numberDic number:(NSString*)number
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *numberID = [numberDic objectFormatStringForKey:@"ID"];
    
    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在修改"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_FLZJ_AU"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"合同ID" value:self.concreteID];
    [content addParameterKey:@"ID" value:numberID];
    [content addParameterKey:@"追加方量" value:number];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        //数据处理
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"修改成功"];
            NSDictionary *mDictionary = [firstArray firstObject];
            
            NSInteger index = [self.resultData indexOfObject:numberDic];
            if(index > self.resultData.count){
                [self.resultData insertObject:mDictionary atIndex:0];
            } else {
                [self.resultData removeObjectAtIndex:index];
                [self.resultData insertObject:mDictionary atIndex:index];
            }
            [self.tableView reloadData];
            
        } else {
            [self showErrorHUDText:@"修改失败"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"修改失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showErrorHUDText:@"网络异常"];
        
    }];
    
}

@end